<template>
  <div>
    <canvas
      id="canvas_sign"
      width="500"
      height="250"
      style="border: solid 1px #1b65ee; background-color: #e5e5e5"
      @mousedown="startDrawing"
      @mousemove="draw"
      @mouseup="endDrawing"
      @mouseout="endDrawing"
    ></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { defineEmits } from "vue";

const emit = defineEmits(["Return"]);
const stateLabel = ref("Ready");
const signImage = ref("");
const deviceSN = ref("");
let isDrawing = false;
let canvas, ctx;

onMounted(() => {
  canvas = document.getElementById("canvas_sign");
  ctx = canvas.getContext("2d");
  ctx.strokeStyle = "#000000"; // 设置画笔颜色
  ctx.lineWidth = 3; // 设置画笔宽度
});

const startDrawing = (e) => {
  isDrawing = true;
  draw(e);
};

const draw = (e) => {
  if (!isDrawing) return;
  const { offsetX, offsetY } = e;
  ctx.lineTo(offsetX, offsetY);
  ctx.stroke();
  ctx.beginPath();
  ctx.moveTo(offsetX, offsetY);
};

const endDrawing = () => {
  if (isDrawing) {
    ctx.beginPath(); // 新建一条路径，从而结束当前绘制
    isDrawing = false;
    saveAndEmit(); // 用户完成签名时调用此函数
  }
};

const clearSign = () => {
  ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布内容
  ctx.beginPath(); // 重置路径
  ctx.fillStyle = "#e5e5e5"; // 设置填充颜色为背景色
  ctx.fillRect(0, 0, canvas.width, canvas.height); // 重新填充背景色
  ctx.fillStyle = "#000000"; // 恢复默认填充颜色
};
const saveAndEmit = () => {
  signImage.value = canvas.toDataURL("image/png");
  emit("Return", signImage.value); // 立刻触发自定义事件并传递数据
};

const saveSignToBase64 = () => {
  signImage.value = canvas.toDataURL("image/png");
  console.log("写字板", signImage.value);
  // 这里可以触发一个事件或者直接处理base64数据
};
defineExpose({ clearSign });
</script>

<style scoped>
div {
  padding: 20px;
}
</style>
